// $Id: extlink.js,v 1.4.2.12 2010/05/26 01:25:56 quicksketch Exp $
(function ($) {

function extlinkAttach(context) {
  // Strip the host name down, removing ports, subdomains, or www.
  var pattern = /^(([^\/:]+?\.)*)([^\.:]{4,})((\.[a-z]{1,4})*)(:[0-9]{1,5})?$/;
  var host = window.location.host.replace(pattern, '$3$4');
  var subdomain = window.location.host.replace(pattern, '$1');

  // Determine what subdomains are considered internal.
  if (Drupal.settings.extlink.extSubdomains) {
    var subdomains = "([^/]*\\.)?";
  }
  else if (subdomain == 'www.' || subdomain == '') {
    var subdomains = "(www\\.)?";
  }
  else {
    var subdomains = subdomain.replace(".", "\\.");
  }

  // Build regular expressions that define an internal link.
  var internal_link = new RegExp("^https?://" + subdomains + host, "i");

  // Extra internal link matching.
  var extInclude = false;
  if (Drupal.settings.extlink.extInclude) {
    extInclude = new RegExp(Drupal.settings.extlink.extInclude.replace(/\\/, '\\'));
  }

  // Extra external link matching.
  var extExclude = false;
  if (Drupal.settings.extlink.extExclude) {
    extExclude = new RegExp(Drupal.settings.extlink.extExclude.replace(/\\/, '\\'));
  }

  // Find all links which are NOT internal and begin with http (as opposed
  // to ftp://, javascript:, etc. other kinds of links.
  // When operating on the 'this' variable, the host has been appended to
  // all links by the browser, even local ones.
  // In jQuery 1.1 and higher, we'd use a filter method here, but it is not
  // available in jQuery 1.0 (Drupal 5 default).
  var external_links = new Array();
  var mailto_links = new Array();
  $("a:not(." + Drupal.settings.extlink.extClass + ", ." + Drupal.settings.extlink.mailtoClass + ")", context).each(function(el) {
    try {
      var url = this.href.toLowerCase();
      if (url.indexOf('http') == 0 && (!url.match(internal_link) || (extInclude && url.match(extInclude))) && !(extExclude && url.match(extExclude))) {
        external_links.push(this);
      }
      else if (url.indexOf('mailto:') == 0) {
        mailto_links.push(this);
      }
    }
    // IE7 throws errors often when dealing with irregular links, such as:
    // <a href="node/10"></a> Empty tags.
    // <a href="http://user:pass@example.com">example</a> User:pass syntax.
    catch(error) {
      return false;
    }
  });

  if (Drupal.settings.extlink.extClass) {
    // Apply the "ext" class to all links not containing images.
    if (parseFloat($().jquery) < 1.2) {
      $(external_links).not('[img]').addClass(Drupal.settings.extlink.extClass).each(function() { if ($(this).css('display') == 'inline') $(this).after('<span class=' + Drupal.settings.extlink.extClass + '></span>'); });
    }
    else {
      $(external_links).not($(external_links).find('img').parents('a')).addClass(Drupal.settings.extlink.extClass).each(function() { if ($(this).css('display') == 'inline') $(this).after('<span class=' + Drupal.settings.extlink.extClass + '></span>'); });
    }
  }

  if (Drupal.settings.extlink.mailtoClass) {
    // Apply the "mailto" class to all mailto links not containing images.
    if (parseFloat($().jquery) < 1.2) {
      $(mailto_links).not('[img]').addClass(Drupal.settings.extlink.mailtoClass).each(function() { if ($(this).css('display') == 'inline') $(this).after('<span class=' + Drupal.settings.extlink.mailtoClass + '></span>'); });
    }
    else {
      $(mailto_links).not($(mailto_links).find('img').parents('a')).addClass(Drupal.settings.extlink.mailtoClass).each(function() { if ($(this).css('display') == 'inline') $(this).after('<span class=' + Drupal.settings.extlink.mailtoClass + '></span>'); });
    }
  }

  if (Drupal.settings.extlink.extTarget) {
    // Apply the target attribute to all links.
    $(external_links).attr('target', Drupal.settings.extlink.extTarget);
  }

  $(external_links).click(function(e) {
    var url = $(this).attr('href');
    var title_pattern = '';
    if (Drupal.settings.extlink.extAlert == '1') { //HTML window...
      e.preventDefault();
      //create the link for the actual href and title...
      var title = $(this).text();
      if (!title) {
	      title = $(this).find('img').attr('alt');
      }

      //check if the current title is inside the array of urls replacements
      title_pattern = Drupal.settings.extlink.extReplacementPattern[url];
      if ((title_pattern == 'undefined') || (title_pattern == '') || (title_pattern == null)) {
        title_pattern = title;
      }

      //replace http or https from the title
      if (Drupal.settings.extlink.removeHttp) {
        title_pattern = title_pattern.replace('http://', '');
        title_pattern = title_pattern.replace('https://', '');
        title = title.replace('http://', '');
        title = title.replace('https://', '');
      }
      
      //remove the last slash if it exists
      if (Drupal.settings.extlink.removeLastSlash) {
        var str = title_pattern;
        if (str.substring(str.length-1, str.length) == '/'){
          title_pattern = title_pattern.substring(0, str.length-1);
        }
        
        str = title;
        if (str.substring(str.length-1, str.length) == '/'){
          title = title.substring(0, str.length-1);
        }
      }
      var target = ' target="'+ $(this).attr('target') +'"';
      var link = '<a class="target-link" href="'+ $(this).attr('href') +'" title="'+ title +'"'+ target +'>'+ $.trim(title_pattern) +'</a>';
      
      //create the replacement itens
      var tags = new Array(/@target_link@/ig, /@target_title@/ig, /@target_title_replaced@/ig, /@base_path@/ig, /@target_url@/ig);
      var itens = new Array(link, title, title_pattern, Drupal.settings.basePath, url);
  
      //made the replaces in the message
      var message = Drupal.settings.extlink.extHtmlText;
      for (var i in tags) {
        message = message.replace(tags[i], itens[i]);
      }

      //add the content of the overlay
      $('body').append(message);
      
      //Fixing problem with IE 6. Set overlay height the same of the site content.
      $('div#ext-overlay-background').height($(document).height());
      
      //bind the close overlay function in the link inside the window
      $('#extlink-message a.target-link').click(function () {
        close_overlay();
      });

      $('#ext-ok-button a').focus();
      
      //bind the ok function
      $('#ext-ok-button').click(function (){
        if (Drupal.settings.extlink.extTarget) {
          close_overlay()//close the overlay
          window.open(url); //open the target link
        }
        else {
          window.location = url;
        }
      });
      //bind the cancel function
      $('#ext-cancel-button').click(function (){
        close_overlay();
      });
      
      $('#ext-close-button').click(function () {
        close_overlay();
      });
    }
    else { //javascript warning  
      return confirm(Drupal.settings.extlink.extAlertText);
    }
  }).mousedown(function (e) { //include the handler for middle button for the mouse
    if (e.which == 2) { 
      $(this).click();
    }
  });;

  // Work around for Internet Explorer box model problems.
  if (($.support && !($.support.boxModel === undefined) && !$.support.boxModel) || ($.browser.msie && parseInt($.browser.version) <= 7)) {
    $('span.ext, span.mailto').css('display', 'inline-block');
  }
}

//close the modal
function close_overlay() {
  $('#ext-overlay-background').remove();
  $('#extlink-message').remove();
}

Drupal.behaviors.extlink = function(context) {
  extlinkAttach(context);
}

})(jQuery);
